$(document).ready(function()
{
	var isAdd = false;
	parent.setIframeHeight("channles", 550);
	
	// 国际化
	$('#cdn_chl_name').text(cdn_i18n.prop('cdn_chl_name') + i18n.prop('colon'));
	$('#cdn_nodeid').text(cdn_i18n.prop('cdn_nodeid') + i18n.prop('colon'));
    $('#cdn_providerid').text(cdn_i18n.prop('cdn_providerid') + i18n.prop('colon'));
	$('#cdn_assetid').text(cdn_i18n.prop('cdn_assetid') + i18n.prop('colon'));
	$('#cdn_sourceurl').text(cdn_i18n.prop('cdn_sourceurl') + i18n.prop('colon'));
	$('#cdn_sourcetype').text(cdn_i18n.prop('cdn_sourcetype') + i18n.prop('colon'));
	$('#cdn_biterate').text(cdn_i18n.prop('cdn_biterate') + i18n.prop('colon'));
	$('#cdn_slicedur').text(cdn_i18n.prop('cdn_slicedur') + i18n.prop('colon'));
	$('#cdn_recordedur').text(cdn_i18n.prop('cdn_recordedur') + i18n.prop('colon'));
	$('#cdn_storepath').text(cdn_i18n.prop('cdn_storepath') + i18n.prop('colon'));
	$('#cdn_isenable').text(cdn_i18n.prop('cdn_isenable') + i18n.prop('colon'));
	$('#cdn_submit').text(cdn_i18n.prop('cdn_submit'));
	$('#cdn_cancel').text(cdn_i18n.prop('cdn_cancel'));
	
	// 条件查询的面板
	var panel = $("#codition_div").omPanel(
	{
        iconCls : "panel_search",
        header : true,
        title : cdn_i18n.prop('cdn_search'),
        collapsed : false,
        collapsible : true
    });
	
	
	
	$('#sourcetype').omCombo(
	{
		dataSource :
		[
				{
					text : '默认',
					value : 'CDefaultRTITask'
				},
				{
					text : 'HLS',
					value : 'CHLSRTITask'
				},
				{
					text : 'HTTP',
					value : 'CHTTPRTITask'
				},
				{
					text : 'UDP',
					value : 'CUDPRTITask'
				}
		],
		width : '80px',
		//emptyText : config_i18n.prop("emptyText"),
		editable : false
	});
	
	$('#isenable').omCombo(
	{
		dataSource :
		[
				{
					text : cdn_i18n.prop("cdn_disable"),
					value : '0'
				},
				{
					text : cdn_i18n.prop("cdn_enable"),
					value : '1'
				}
		],
		width : '80px',
		//emptyText : config_i18n.prop("emptyText"),
		editable : false
	});
	
	// 把查询的表单加入到面板当中
	$("#condition_query").append($("form[name='codition_form']"));
	
	// 修改图标
	$(".panel_search").removeClass("om-icon");
	$(".panel_search").removeClass("om-panel-icon");
	
	// 渲染查询按钮
	$("#cod_btn_search").omButton(
	{
		label : cdn_i18n.prop('usmc_user_search'),
		icons : 
		{
			left : '../../component/css/omui/default/images/search.png'
		},
		width : 80,
		onClick : function(event)
		{
			//var username = encodeURIComponent($.trim($('input[name="cod_abyEnbName"]').val()));
			//$('#usmc_userinfoGrid').omGrid("setData", '/api/usmc/v1/userbyname?username=' + username);
			// 按钮失去焦点
			//$(this).blur();
		}
	});
	
	// 回车事件
	// 点击“Enter”键，触发查询事件
	$(this).keydown(function(e)
	{
		if (e.which == "13")
		{
			if(document.getElementsByName('cod_abyEnbName')[0] == document.activeElement)
			{
				//var username = encodeURIComponent(encodeURIComponent($.trim($('input[name="cod_abyEnbName"]').val())));
				//$('#usmc_userinfoGrid').omGrid("setData", '/api/usmc/v1/userbyname?username=' + username);
				
				return true;
			}
		}
	});
	
	// 渲染清空按钮
	$("#cod_btn_clear").omButton(
	{
		label : cdn_i18n.prop('cdn_reset'),
		icons : 
		{
			left : '../../component/css/omui/default/images/clear.png'
		},
		width : 80,
		onClick : function(event)
		{
			//$('input[name=cod_abyEnbName]').val('');
			//$('input[name=cod_abyEnbName]').focus();

			// 按钮失去焦点
			$(this).blur();
		}
	});
	
	
	// 初始化botton按钮
	$('#buttonbar').omButtonbar(
	{
		btns :
		[
			{
				label : cdn_i18n.prop('cdn_delete'),
				id : "cdn_delete",
				icons :
				{
					left : '../../component/css/omui/default/images/del_hover.png'
				},
				onClick : function()
				{
					
					deleteChannle();
				}
			},
			
			{
				separtor : true
			},
			
			{
				label : cdn_i18n.prop('cdn_modify'),
				id : "cdn_modify",
				icons :
				{
					left : '../../component/css/omui/default/images/edit_hover.png'
				},
				onClick : function()
				{
					modifyChannle();
				}
			},
			
			{
				separtor : true
			},
			
			{
				label : cdn_i18n.prop('cdn_add'),
				id : "cdn_add",
				icons :
				{
					left : '../../component/css/omui/default/images/add_hover.png'
				},
				onClick : function()
				{
					addChannle();
				}
			}
		]
	});
	
	// 创建表格
	$("#cdn_channleoGrid").omGrid(
	{
		dataSource : "/api/v1/resource/channles",
		limit : Omui.TABLE_ROWS,
		height : Omui.TABLE_HEIGHT,
		singleSelect : true,
		showIndex : true,
		colModel :
		[
			{
				header : cdn_i18n.prop("cdn_chl_name"),
				name : 'channelname',
				width : 150,
				align : 'left'
			},
			
			/*{
				header : cdn_i18n.prop("usmc_UserRole"),
				name : 'userRole',
				width : 180,
				align : 'left',
				renderer : function(v, rowData , rowIndex)
				{
					if("1" == v)
					{
						return cdn_i18n.prop("com_raisecom_itms_hnb_tdHnbState1");
					}
					else
					{
						return cdn_i18n.prop("com_raisecom_itms_hnb_tdHnbState2");
					}
				}
			},*/

			{
				header : '节点ID',
				name : 'nodeid',
				width : 100,
				align : 'left'
			},
			{
				header : cdn_i18n.prop("cdn_providerid"),
				name : 'providerid',
				width : 100,
				align : 'left'
			},
			
			{
				header : cdn_i18n.prop("cdn_assetid"),
				name : 'assetid',
				width : 100,
				align : 'left'
			},
			
			{
				header : cdn_i18n.prop("cdn_sourceurl"),
				name : 'sourceurl',
				width : 180,
				align : 'left'
			}
		   ,
		   
			{
				header : cdn_i18n.prop("cdn_sourcetype"),
				name : 'sourcetype',
				width : 180,
				align : 'left',
				renderer : function(v, rowData , rowIndex)
				{
					if("CDefaultRTITask" == v)
					{
						return '默认';
					}
					else if("CHLSRTITask" == v)
					{
						return 'HLS';
					}
					else if('CHTTPRTITask' == v)
					{
						return 'HTTP';
					}
					else if('CUDPRTITask' == v)
					{
						return 'UDP';
					}
				}
			}
		   ,
		   
			{
				header : cdn_i18n.prop("cdn_biterate"),
				name : 'biterate',
				width : 100,
				align : 'left'
			},
			
			{
				header : cdn_i18n.prop("cdn_slicedur"),
				name : 'slicedur',
				width : 100,
				align : 'left'
			},
			
			{
				header : cdn_i18n.prop("cdn_recordedur"),
				name : 'recordedur',
				width : 100,
				align : 'left'
			}
,
			
			{
				header : cdn_i18n.prop("cdn_storepath"),
				name : 'storepath',
				width : 180,
				align : 'left'
			}
			,
			
			{
				header : cdn_i18n.prop("cdn_isenable"),
				name : 'isenable',
				width : 80,
				align : 'left',
				renderer : function(v, rowData , rowIndex)
				{
					if("0" == v)
					{
						return '<span style="color:red">' + cdn_i18n.prop("cdn_disable") +' </span>';
					}
					else
					{
						return '<span style="color:green">' + cdn_i18n.prop("cdn_enable") +' </span>';
					}
				}
			}
		],
		onRefresh : function(data, testStatus, XMLHttpRequest, event)
		{
			// 隐藏勾选框
			$(".checkboxCol").hide();
		}
	});
	
	
	// 新增按钮
	var addChannle = function()
	{
		isAdd = true;
		showDialog(cdn_i18n.prop('cdn_add'));
	};
	
	// 修改信息
	var modifyChannle = function()
	{
		isAdd = false;
		var selections = $('#cdn_channleoGrid').omGrid('getSelections', true);
		
		if (selections.length == 0)
		{
			alertUnCheckWarn();
			return false;
		}
		
		showDialog(cdn_i18n.prop('cdn_modify'), selections[0]);
	};
	
	// 删除信息
	var deleteChannle = function()
	{
		var selections = $('#cdn_channleoGrid').omGrid('getSelections', true);
		if (selections.length == 0)
		{
			alertUnCheckWarn();
		}
		else
		{
			$.omMessageBox.confirm(
			{
				title : i18n.prop("alert"),
				content : i18n.prop("deleteContent"),
				onClose : function(value)
				{
					if (value)
					{
						// 提交删除请求
						$.ajax(
						{
							type : 'DELETE',
							url : '/api/v1/resource/channles/' + selections[0].id,
							dataType : 'json',
//							data : JSON.stringify(request),
							contentType : 'application/json',
							success : function(msg)
							{
								// 提示消息
								if (msg.result == "0")
								{
									// 更新表格
									$('#cdn_channleoGrid').omGrid('reload');
									
									// 删除成功提示
									alertSuccess();
								}
								else
								{
									// 删除失败提示
									alertFail();
								}
							}
						});
					}
				}
			});
		}
	};
	
	
	// 定义修改或添加的弹出框
	var dialog = $("#add_dialog-form").omDialog(
	{
		width : '50%',
		autoOpen : false,
		modal : true,
		resizable : false,
		onClose : function(event)
		{
			// 清除红框样式
			$("input").removeClass("x-form-invalid");
		}
	});
	
	// 显示修改或增加的弹出框
	var showDialog = function(title, rowData)
	{
		//validator.resetForm();
		
		// 设置表格提示信息
		var trs = $('table tr', dialog);
		
		// input disable
		// $("#id").removeAttr("disabled");
//		$("#userbingip").attr("disabled", "disabled");
//		$("#useruserexpiry").attr("disabled", "disabled");
//		$("#userpassexpiry").attr("disabled", "disabled");
//		$("#usersessionexpiry").attr("disabled", "disabled");
		
		rowData = rowData || {};
		
		$('input[name=channelname]', dialog).val(rowData.channelname);
		//$('input[name=userpasswd]', dialog).val(rowData.hnbIpAddr);
		$('input[name=providerid]', dialog).val(rowData.providerid);
		$('input[name=nodeid]', dialog).val(rowData.nodeid);
		$('input[name=assetid]', dialog).val(rowData.assetid);
		$('input[name=sourceurl]', dialog).val(rowData.sourceurl);
		// $('input[name=sourcetype]', dialog).val(rowData.sourcetype);
		$('input[name=biterate]', dialog).val(rowData.biterate);
		
		$('input[name=slicedur]', dialog).val(rowData.slicedur);
		$('input[name=recordedur]', dialog).val(rowData.recordedur);
		$('input[name=storepath]', dialog).val(rowData.storepath);
		if(rowData.sourcetype == null || rowData.sourcetype == '')
		{
			$('#sourcetype').omCombo('value', 'CDefaultRTITask');
		}
		else
		{
			$('#sourcetype').omCombo('value', rowData.sourcetype);
		}
		if(rowData.isenable == null || rowData.isenable == '')
		{
			$('#isenable').omCombo('value', '0');
		}
		else
		{
			$('#isenable').omCombo('value', rowData.isenable);
		}
		
		// channelname can not modify here
		if (isAdd)
		{
			$('input[name=channelname]', dialog).removeAttr("disabled");
		}
		else
		{
			$('input[name=channelname]', dialog).attr("disabled", "disabled");
		}
		
		dialog.omDialog("option", "title", title);
		dialog.omDialog("open");
	};
	
	// 弹出框取消按钮
	$('#cdn_cancel').click(function()
	{
		$("#add_dialog-form").omDialog("close");
		
		// 清除红框样式
		$("input").removeClass("x-form-invalid");
		return false;
	});
	
	// 弹出框确定按钮：添加or修改
	$('#cdn_submit').click(function()
	{
		dataSubmitDialog();
		return false;
	});
	
	// 弹出框确定按钮的具体操作
	var dataSubmitDialog = function()
	{
		//if (validator.form())
		if (true)
		{
			var selections = $('#cdn_channleoGrid').omGrid('getSelections', true);
			var submitData = null;
			
			var urls = "/api/v1/resource/channles";
			
			if (isAdd)
			{
				submitData = 
				{
					channelname : $('input[name=channelname]', dialog).val(),
					providerid : $('input[name=providerid]', dialog).val(),
					nodeid : $('input[name=nodeid]', dialog).val(),
					assetid : $('input[name=assetid]', dialog).val(),
					sourceurl : $('input[name=sourceurl]', dialog).val(),
					// sourcetype : $('input[name=sourcetype]', dialog).val(),
					sourcetype : $('input[name=sourcetype]', dialog).omCombo('value'),
					biterate : $('input[name=biterate]', dialog).val(),
					slicedur : $('input[name=slicedur]', dialog).val(),
					recordedur : $('input[name=recordedur]', dialog).val(),
					storepath : $('input[name=storepath]', dialog).val(),
					isenable : $("input[name=isenable]", dialog).omCombo('value')
				};
				
				$.ajax(
				{
					type : 'POST',
					url : urls,
					dataType : 'json',
					data : JSON.stringify(submitData),
					contentType : 'application/json',
					success : function(msg)
					{
						// 查询到的JSON对象
						if (msg.result == "0")
						{
							alertSuccess();
							// 关闭dialog
							$("#add_dialog-form").omDialog("close");
							
							// 清除红框样式
							$("input").removeClass("x-form-invalid");
							
							// 更新表格
							$('#cdn_channleoGrid').omGrid('reload');
						}
						else
						{
							alertFail();
						}
					}
				});
			}
			else
			{
				submitData = 
				{
					id : selections[0].id,
					channelname : $('input[name=channelname]', dialog).val(),
					providerid : $('input[name=providerid]', dialog).val(),
					nodeid : $('input[name=nodeid]', dialog).val(),
					assetid : $('input[name=assetid]', dialog).val(),
					sourceurl : $('input[name=sourceurl]', dialog).val(),
					//sourcetype : $('input[name=sourcetype]', dialog).val(),
					sourcetype : $('input[name=sourcetype]', dialog).omCombo('value'),
					biterate : $('input[name=biterate]', dialog).val(),
					slicedur : $('input[name=slicedur]', dialog).val(),
					recordedur : $('input[name=recordedur]', dialog).val(),
					storepath : $('input[name=storepath]', dialog).val(),
					isenable : $("input[name=isenable]", dialog).omCombo('value')
				};
				
				$.ajax(
				{
					type : 'PUT',
					url :urls,
					dataType : 'json',
					data : JSON.stringify(submitData),
					contentType : 'application/json',
					success : function(msg)
					{
						// 查询到的JSON对象
						if (msg.result == "0")
						{
							alertSuccess();
							// 关闭dialog
							$("#add_dialog-form").omDialog("close");
							
							// 清除红框样式
							$("input").removeClass("x-form-invalid");
							
							// 更新表格
							$('#cdn_channleoGrid').omGrid('reload');
						}
						else
						{
							alertFail();
						}
					}
				});
			}
		}
	};
	
	
	// 过滤字段
	var rules =
	{
		username :
		{
			required : true,
			lengthrange :
			[
				1, 32
			],
			// isQuote : true,
			// isChinese : true,
			isCorrectString : true
		},
		userpasswd :
		{
			required : true,
			lengthrange :
			[
				6, 64
			],
			isChinese : true
		},
		userbingip :
		{
			isIp : true
		},
		usermail :
		{
			// required : true,
			email: true,
			isChinese : true
		},
		userphone :
		{
			// required : true,
			isMobilPhone : true
		}	
	};
	
	// 提示消息
	var errMsgs =
	{
		username :
		{
			required : cdn_i18n.prop('usmc_not_empty'),
			lengthrange : cdn_i18n.prop('usmc_user_nameTooLong')
		},
		userpasswd :
		{
			required : cdn_i18n.prop('usmc_not_empty'),
			lengthrange : cdn_i18n.prop('usmc_passTooshort')
		},
		userbingip :
		{
			isIp : cdn_i18n.prop('usmc_ipNotRight')
		},
		usermail :
		{
			required : cdn_i18n.prop('usmc_not_empty'),
			email :	cdn_i18n.prop('usmc_user_mail_err')
		},
		userphone :
		{
			required : cdn_i18n.prop('usmc_not_empty'),
		}	
	};
	
	// 调用验证方法，创建验证对象
	var validator = new form_validator(rules, errMsgs, 'errorMsg', 'userInfoForm');
	
	// 验证特殊字符
    $.validator.addMethod("isQuote", function(value) {
        return checkQuote(value);
    }, cdn_i18n.prop('usmc_user_include_special_sign'));
	
    function checkQuote(str){
        var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "{", "}", "[", "]", "(", ")");
        items.push(":", ";", "'", "|", "\\", "<", ">", "?", "/", "<<", ">>", "||", "//");
        // items.push("admin", "administrators", "administrator", "管理员", "系统管理员");
        // items.push("select", "delete", "update", "insert", "create", "drop", "alter", "trancate");
        str = str.toLowerCase();
        for (var i = 0; i < items.length; i++) {
            if (str.indexOf(items[i]) >= 0) {
                return false;
            }
        }
        return true;
    }
    
    // 验证是否包含中文
    $.validator.addMethod("isChinese", function(value) {
        return checkChinese(value);
    }, cdn_i18n.prop('usmc_user_include_chinese'))
    
    function checkChinese(str){
        if (escape(str).indexOf("%u") != -1) {
            return false;
        }
        else {
            return true;
        }
    }
    
    $.validator.addMethod("isMobilPhone", function(value) 
    {
    	if (0 == value.length)
    	{
    		return true;
    	}	
    	
      var regu =/(^[1][3][0-9]{9}$)|(^[1][5][0-9]{9}$)|(^[1][8][0-9]{9}$)|(^[0][1-9]{1}[0-9]{9}$)/; 
      var reg = new RegExp(regu);
      return reg.test(value);  // 手机验证 13x 15x 18x 以此类推
 
    }, cdn_i18n.prop('usmc_user_mobilphone_err'));

    $.validator.addMethod("isCorrectString", function(value) {
        var regu =/(^[a-zA-Z_0-9]*$)/; 
        var reg = new RegExp(regu);
        return reg.test(value); 
    }, cdn_i18n.prop('usmc_user_string_err'));
     
});
